<!-- eslint-disable no-unreachable -->
<template>
  <div>

    <el-container>
      <!-- 搜索栏 -->
      <el-header>
        <el-row :gutter="20" style="padding: 5px 20px;">
          <el-col :span="6"><el-input v-model.trim="searchModel.itemName" placeholder="项目名称" clearable @keyup.enter.native="getitemList" /></el-col>
          <el-col :span="6"><el-button type="primary" round icon="el-icon-search" @click="getItemList">搜索</el-button></el-col>
          <el-col align="right" :span="6"><el-button type="primary" round icon="el-icon-plus" @click="handleDialogVisible(null)">新增</el-button></el-col>
        </el-row>
      </el-header>

      <!-- 结果列表 -->
      <el-main>
        <el-table :data="list" style="width: 100%;" :header-cell-style="centerHeaderStyle" :cell-style="centerCellStyle">
          <el-table-column type="index" label="index" width="100">
            <template slot-scope="scope">
              {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="itemName" label="项目名称" width="150" />
          <el-table-column prop="itemNumber" label="项目编码" width="100" />
          <el-table-column prop="itemAddress" label="项目地址" />
          <el-table-column prop="itemPhone" label="联系方式" />
          <!-- 查看组织 -->
          <el-table-column prop="orgId" label="组织">
            <template slot-scope="scope">
              <el-popover
              placement="right"
              width="400"
              trigger="click">
              <el-form label-width="80px" :model="orgForm" label-position="left">
                <el-form-item label="组织名称">
                  <el-input v-model="orgForm.orgDept" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="联系地址">
                  <el-input v-model="orgForm.orgRegion" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="组织类型">
                  <el-input v-model="orgForm.orgType" :disabled="true"></el-input>
                </el-form-item>
              </el-form>
              <el-button slot="reference" @click="getOrgList(scope.row.orgId)">查看组织</el-button>
            </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                @click="handleDialogVisible(scope.row.itemId)"
              >修改</el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteItem(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>

      <!-- 分页 -->
      <el-footer>
        <el-pagination
          :current-page="searchModel.pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="searchModel.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-footer>
    </el-container>

    <!-- 修改框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearForm">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="itemNumber" label="项目编号" :label-width="formLabelWidth">
          <el-input v-model="form.itemNumber" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="itemName" label="项目名称" :label-width="formLabelWidth">
          <el-input v-model="form.itemName" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="itemAddress" label="项目地址" :label-width="formLabelWidth">
          <el-cascader style="width: 100%;"
            placeholder="请选择地址"
            size="large"
            :options="pcaTextArr"
            v-model="form.itemAddress"
            clearable
            ></el-cascader>
        </el-form-item>
        <el-form-item prop="itemPhone" label="项目电话" :label-width="formLabelWidth">
          <el-input v-model="form.itemPhone" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="orgId" label="所属机构" :label-width="formLabelWidth">
            <el-select v-model="form.orgId" placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="item in orgForms"
                :key="item.orgId"
                :label="item.orgDept"
                :value="item.orgId">
              </el-option>
            </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import itemRequest from '@/api/itemManage'
import organizationRequest from '@/api/organizationManage'
import { pcaTextArr  } from 'element-china-area-data'

export default {
  data() {
    return {
      pcaTextArr,
      totalPage: 0,
      searchModel: {
        itemName: '',
        pageNo: 1,
        pageSize: 10
      },
      list: [],
      dialogFormVisible: false, // 对话框显示隐藏
      form: {
      },
      formLabelWidth: '150px',
      title: '',
      orgForm: {},
      orgForms: {},
      rules: {
        itemName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getItemList()
    this.getOrgForms()
  },
  methods: {
    getOrgForms() {
      organizationRequest.getAllOrganizationList().then(response => {
        this.orgForms = response.data
      })
    },
    getOrgList(orgId) {
      organizationRequest.getOrganizationById(orgId).then(response => {
        if (response.code === 20000) {
          this.$notify({
            title: '成功',
            message: '查看成功',
            type: 'success'
          })
          this.orgForm = response.data
        } 
      })
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getItemList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getItemList()
    },
    getItemList() { 
      // then是调完后的回调方法
      // 在then中把数据传回过来, total 和 list要复制
      itemRequest.getItemList(this.searchModel).then(response => {
        this.totalPage = response.data.totalPage
        this.list = response.data.rows
      })
    },
    handleDialogVisible(id) {
      if (id == null) {
        this.title = '新增项目'
      } else {
        this.title = '修改项目'
        itemRequest.getItemById(id).then(response => {
          this.form = response.data
          let addressText = response.data.itemAddress
          let addressArr = addressText.split("--")

          this.form.itemAddress = addressArr

        })
      }

      this.dialogFormVisible = true
    },
    clearForm() {
      this.form = {}
      this.$refs.formRef.clearValidate()
    },
    handleSave() {
      // 触发表单验证
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          itemRequest.saveItem(this.form).then(response => {
            // 成功提示
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭表格
            this.dialogFormVisible = false
            // 刷新表格
            this.getItemList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    deleteItem(item) {
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        itemRequest.deleteItemById(item.itemId).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getItemList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    timestampToTime(timestamp) {
      timestamp = timestamp ? timestamp : null;
      let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + '-';
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    centerHeaderStyle({ row, column, rowIndex, columnIndex }) {
      return { 'text-align': 'center' };
    },
    centerCellStyle({ row, column, rowIndex, columnIndex }) {
      return { 'text-align': 'center' };
    },
  }
}
</script>

<style>
  .el-dialog .el-input {
    width: 70%;
  }
</style>
